/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.buss.core.validator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import com.buss.core.utils.StringUtil;

/**
 *
 * @author gykl
 */
public class RegularValidValidator implements ConstraintValidator<RegularValid, String>{

    private Pattern pattern;

    public void initialize(RegularValid parameters) {
        RegularValid.Flag[] flags = parameters.flags();
        int intFlag = 0;
        for(RegularValid.Flag flag : flags){
            intFlag |= flag.getValue();
        }
        try{
            this.pattern = Pattern.compile(parameters.regexp(), intFlag);//java.util.regex.Pattern.compile(rv.regexp(),intFlag);
        }catch(PatternSyntaxException e){
            throw new IllegalArgumentException("Invalid regular expression.",e);
        }
    }

    public boolean isValid(String value, ConstraintValidatorContext cvc) {
        if(StringUtil.isEmpty(value)){
            return true;
        }
        Matcher m = this.pattern.matcher(value);
        System.out.println(m.matches());
        return m.matches();
    }

}
